package com.bishe.psy.controller;

import com.bishe.psy.common.AppResult;
import com.bishe.psy.common.ResultCode;
import com.bishe.psy.config.AppConfig;
import com.bishe.psy.exception.ApplicationException;
import com.bishe.psy.model.ConUser;
import com.bishe.psy.model.StuUser;
import com.bishe.psy.service.IConUserService;
import com.bishe.psy.utils.MD5Util;
import com.bishe.psy.utils.StringUtil;
import com.bishe.psy.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: L
 * Date: 2024-03-28
 * Time: 17:45
 */

@Slf4j
@Api(tags = "咨询师用户接口")
@RestController
@RequestMapping("/con")
public class ConUserController {


    @Resource
    private IConUserService iConUserService;

    @ApiOperation("咨询师登录方法")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam(value ="用户名") @RequestParam("username") String username,
                           @ApiParam(value ="密码")  @RequestParam("password") String password) {

        //1.参数校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //2.调用service
        ConUser conUser = iConUserService.login(username, password);

        //登录成功，把User对象设置到session作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,conUser);

        return AppResult.success();
    }


    @ApiOperation("获取咨询师信息详情")
    @GetMapping("/coninfo")
    public AppResult<ConUser> getConUserInfo(HttpServletRequest request,
                                             @ApiParam(value ="咨询师id") @RequestParam(value = "id",required = false) Long id ) {

        ConUser conUser = null;
        //参数校验
        if(id == null) {
            //id为空时，此时从session中获取当前登录用户的信息
            HttpSession session = request.getSession(false);
            //检验session的值
            //校验通过，取出当前用户信息
            conUser = (ConUser) session.getAttribute(AppConfig.USER_SESSION);
        } else {

            //当id不为空时，此时需要从数据库中查询用户信息
            conUser = iConUserService.selectByPrimaryKey(id);
        }
        //检验用户是否存在
        if(conUser == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //返回jason数据给前端
        return AppResult.success(conUser);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {

        //获取session对象
        HttpSession session = request.getSession(false);
        if(session != null) { //表示当前对象已登录
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @ApiOperation("咨询师修改个人信息")
    @PostMapping("/modifyCon")
    public AppResult modifyConInfo(HttpServletRequest request,
                                   @ApiParam(value = "用户昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                   @ApiParam(value = "电话号码") @RequestParam(value = "phoneNum",required = false)String phoneNum,
                                   @ApiParam(value = "邮箱") @RequestParam(value = "email",required = false)String email,
                                   @ApiParam(value = "咨询师类型") @RequestParam(value = "type",required = false)String type,
                                   @ApiParam(value = "简介") @RequestParam(value = "remark",required = false)String remark) {

        //1.参数校验，当传入的数据都为空时，异常
        if(StringUtil.isEmpty(nickname) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(type) && StringUtil.isEmpty(remark)) {
            return AppResult.failed("请输入要修改的内容");
        }

        //2.获取登录信息
        HttpSession session = request.getSession(false);
        ConUser conUser = (ConUser) session.getAttribute(AppConfig.USER_SESSION);

        //3.封装对象
        ConUser updateCon = new ConUser();
        updateCon.setId(conUser.getId());
        updateCon.setNickname(nickname);
        updateCon.setPhoneNum(phoneNum);
        updateCon.setEmail(email);
        updateCon.setType(type);
        updateCon.setRemark(remark);

        //4.调用service
        iConUserService.modifyConInfo(updateCon);

        //5.获取最新的信息
        conUser = iConUserService.selectByPrimaryKey(conUser.getId());

        //6.更新到session中
        session.setAttribute(AppConfig.USER_SESSION,conUser);

        //7.返回数据
        return AppResult.success(conUser);

    }

    @ApiOperation("修改密码接口")
    @PostMapping("/modifyPsw")
    public AppResult modifyPassWord(HttpServletRequest request,
                                    @ApiParam(value = "旧密码")  @RequestParam("oldPassword") String oldPassword,
                                    @ApiParam(value = "新密码")  @RequestParam("newPassword")String newPassword,
                                    @ApiParam(value = "确认密码")  @RequestParam("confirmPassword")String confirmPassword) {

        //1.获取用户信息
        HttpSession session = request.getSession(false);
        ConUser conUser = (ConUser) session.getAttribute(AppConfig.USER_SESSION);

        //2.判断确认和新密码是否一样

        if(!newPassword.equals(confirmPassword)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //3.调用service
        iConUserService.modifyPassword(conUser.getId(),oldPassword,newPassword);


        //4.销毁session
        if(session != null) {
            session.invalidate();
        }

        //5.返回结构
        return AppResult.success();
    }

    @ApiOperation("获取所有咨询师账号信息")
    @GetMapping("/selectAll")
    public AppResult<List<ConUser>> selectAll() {

        //1.调用service
        List<ConUser> conUsers = iConUserService.selectAllInfo();

        //2.返回结果
        return AppResult.success(conUsers);

    }

    @ApiOperation("删除咨询师账号")
    @GetMapping("/update")
    public AppResult updateDeleteState(@ApiParam(value = "用户名") @RequestParam("username")String username) {

        //1.参数校验
        if(StringUtil.isEmpty(username)) {
            return AppResult.failed("用户不存在");
        }

        //2.调用service
        iConUserService.updateDeleteStateByUsername(username);

        //2.返回结果
        return AppResult.success();

    }

    @ApiOperation("用户注册方法")
    @PostMapping("/register")
    public AppResult register (@ApiParam(value = "⽤⼾名") @RequestParam("username") String username, @ApiParam(value = "昵称") @RequestParam("nickname") String nickname,
                               @ApiParam(value = "性别")  @RequestParam("gender")String gender, @ApiParam(value = "密码")  @RequestParam("password") String password,
                               @ApiParam(value = "咨询师类型") @RequestParam("type") String type, @ApiParam(value = "确认密码")  @RequestParam("passwordRepeat") String passwordRepeat) {

        System.out.println("-----------------");
        System.out.println(gender);
        System.out.println("-----------------");


        //1.前端传入数据参数校验
        if(StringUtil.isEmpty(username) ||StringUtil.isEmpty(nickname) || StringUtil.isEmpty(type)
                || StringUtil.isEmpty(gender) || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //2.密码校验
        //判断前端界面输入的两次密码是否一样
        if(!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //3.明文密码处理变成密文
        String salt = UUIDUtil.UUID_32();
        //写在数据库中的密码
        String ciphertext = MD5Util.md5(password ,salt);

        //4.新用户赋值
        ConUser conUser = new ConUser();

        conUser.setUsername(username);
        conUser.setNickname(nickname);
        conUser.setGender(gender);
        conUser.setSalt(salt);
        conUser.setPassword(ciphertext);
        conUser.setType(type);

        //5.调用service，往数据库插入新用户
        iConUserService.createCon(conUser);

        return AppResult.success();

    }


}
